//
//  NetworkRequest.swift
//  MevosSwift
//
//  Created by roy on 2017/4/18.
//  Copyright © 2017年 roy. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import CryptoSwift

typealias successBlock = (Any)->Any
typealias failBlock = (Any)->Any



private let NetworkRequestShareInstance = NetworkRequest()

class NetworkRequest: NSObject {
    var successRBlock: successBlock?
    var failRBlock : failBlock?
    public typealias Parameters = [String: Any]
    class var shareInstance: NetworkRequest {
        return NetworkRequestShareInstance
        
    }
}

extension NetworkRequest{
    // GET 请求
    func getRequest(urlString:String, params:Dictionary<String, Any>, success: @escaping (_ response:[String:AnyObject])->(),failtrue : @escaping (_ error : Error)->()) {
        //[String : AnyObject]类型 返回void类型的函数
        Alamofire.request(urlString, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).validate().responseJSON{
            (response) in   /*这里使用了闭包*/
                            switch response.result {
                            case .success(let value):
                                
                                success(value as! [String : AnyObject])
                                //                    }
                                let json = JSON(value)
                                self.successRBlock!(json)
                                print(json)
            
                            case .failure(let error):
                                failtrue(error)
                                //self.failRBlock!(error)
                                print("error:\(error)")
                            }
        }
        
//        Alamofire.request(urlString, method: .get, parameters: params)
//            .responseJSON {
//                (response) in   /*这里使用了闭包*/
//                switch response.result {
//                case .success(let value):
//                    //当响应成功是，使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success
//                    //                    if let value = response.result.value as? [String: AnyObject] {
//                    success(value as! [String : AnyObject])
//                    //                    }
//                    let json = JSON(value)
//                    self.successRBlock!(json)
//                    print(json)
//                    
//                case .failure(let error):
//                    failtrue(error)
//                    self.failRBlock!(error)
//                    print("error:\(error)")
//                }
//        }
        
    }
    // POST 请求
    func postRequest(urlString : String, params : Parameters? = nil, success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) {
        
        Alamofire.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).validate().responseJSON{ (response) in
            switch response.result{
            case .success:
                if let value = response.result.value as? [String: AnyObject] {
                    let json = JSON(value)
                    if json["code"].intValue == 0{
                        success(value)
                        
                    }
                    //print(json)
                }
            case .failure(let error):
                failture(error)
                print("error:\(error)")
            }
            
        }
    }
    //MARK: - 照片上传
    /// - Parameters:
    ///   - params: ["flag":"","userId":""] - flag,userId 为必传参数
    ///        flag - 666 信息上传多张  －999 服务单上传  －000 头像上传
    ///   - data: image转换成Data
    ///   - name: fileName
    ///   - success:
    ///   - failture:
    func upLoadImageRequest(urlString : String, params:[String:String], data: [Data], name: [String],success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){
        
        let headers = ["content-type":"multipart/form-data"]
        
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                //666多张图片上传
                let flag = params["flag"]
                let userId = params["userId"]
                
                multipartFormData.append((flag?.data(using: String.Encoding.utf8)!)!, withName: "flag")
                multipartFormData.append( (userId?.data(using: String.Encoding.utf8)!)!, withName: "userId")
                
                for i in 0..<data.count {
                    multipartFormData.append(data[i], withName: "appPhoto", fileName: name[i], mimeType: "image/png")
                }
        },
            to: urlString,
            headers: headers,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        if let value = response.result.value as? [String: AnyObject]{
                            success(value)
                            let json = JSON(value)
                            print(json)
                        }
                    }
                case .failure(let encodingError):
                    print(encodingError)
                    failture(encodingError)
                }
        }
        )
    }
    
    private func buildParams(_ parameters: [String: Any]) -> String {
        var components: [(String, String)] = []
        
        for key in parameters.keys.sorted(by: <) {
            let value = parameters[key]!
            components += queryComponents(fromKey: key, value: value)
        }
        
        return components.map { "\($0)=\($1)" }.joined(separator: "&")
    }
    
    public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
        var components: [(String, String)] = []
        
        if let dictionary = value as? [String: Any] {
            for (nestedKey, value) in dictionary {
                components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
            }
        } else if let array = value as? [Any] {
            for value in array {
                components += queryComponents(fromKey: "\(key)[]", value: value)
            }
        } else if let value = value as? NSNumber {
            if value.boolValue {
                components.append((escape(key), escape((value.boolValue ? "1" : "0"))))
            } else {
                components.append((escape(key), escape("\(value)")))
            }
        } else if let bool = value as? Bool {
            components.append((escape(key), escape((bool ? "1" : "0"))))
        } else {
            components.append((escape(key), escape("\(value)")))
        }
        
        return components
    }
    
    
    
    public func escape(_ string: String) -> String {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="
        
        var allowedCharacterSet = CharacterSet.urlQueryAllowed
        allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
        
        return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
    }
    
}
